import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LKQ
 * @date 2022/2/22 11:01
 * @description 桶排序
 */
public class FormalSolution {
    public static void main(String[] args) {
        FormalSolution solution = new FormalSolution();
        int[] nums = {1, 2};
        solution.topKFrequent(nums, 2);
    }
    public int[] topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();
        // 字典统计每个数字出现次数
        Map<Integer, Integer> frequencyMap = new HashMap<>();
        for (int num: nums) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num,0) + 1);
        }
        // 桶排序，将频率作为数组下标，对于出现频率不同的数字集合，存入对应的数字下标
        List<Integer>[] list = new List[nums.length + 1];
        for (int key: frequencyMap.keySet()) {
            // 出现次数
            int i = frequencyMap.get(key);
            if (list[i] == null) {
                // 为空则初始化
                list[i] = new ArrayList<>();
            }
            list[i].add(key);
        }
        // 倒序遍历出现顺序前k的个数
        int[] ans = new int[k];
        int start = 0;
        for (int i = list.length - 1; i >= 0 && start < k; i--) {
            if (list[i] == null) {
                continue;
            }
            for (int j = 0; j < list[i].size() && start < k; j++) {
                ans[start++] = list[i].get(j);
            }
        }
        return ans;
    }
}
